package cn.jtfadmin.base.lang.config.statuscode;

import cn.jtfadmin.base.lang.config.WebConfig;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * sql 数据库错误
 *
 * @author jtf
 * @see StatusCodeConfig
 * @see StatusCodeManager
 * @see WebConfig#configureHandlerExceptionResolvers(List)
 * @since 0.0.1
 */
@Component
public class SqlErrorStatusCodeConfig implements ExceptionStatusCodeConfig {

    /**
     * 用户名或密码错误
     */
    public static final Integer ERROR = 503;
    public static final String ERROR_MSG = "数据库错误";


    public static final ExceptionStatusDescribe DEFAULT_ERROR_STATUS_DESCRIBE =
            new ExceptionStatusDescribe(ERROR_MSG, ERROR, SQLIntegrityConstraintViolationException.class,SQLException.class) {
                @Override
                public String getDescribe(Throwable throwable) {
                    List<Throwable> throwables = ExceptionStatusCodeConfig.getCause(throwable);
                    for (Throwable ex : throwables) {
                        if (ex instanceof SQLIntegrityConstraintViolationException) {
                            SQLException sqlException = SQLIntegrityConstraintViolationException.class.cast(ex);
                            return "数据约束错误，请先删除关联内容";
                        }
                        if (ex instanceof SQLException) {
                            SQLException sqlException = SQLException.class.cast(ex);
                            return sqlException.getMessage();
                        }
                    }
                    return super.getDescribe(throwable);
                }
            };

    @Override
    public Set<ExceptionStatusDescribe> getExStatusDecribes() {
        Set<ExceptionStatusDescribe> set = new HashSet<>();
        set.add(DEFAULT_ERROR_STATUS_DESCRIBE);
        return set;
    }


}
